package net.lgy.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.lgy.component.StoreEngine;
import net.lgy.config.AccountConfig;
import net.lgy.config.MinioConfig;
import net.lgy.controller.request.AccountLoginRequest;
import net.lgy.controller.request.FolderCreateRequest;
import net.lgy.dto.AccountDTO;
import net.lgy.manager.AccountManager;
import net.lgy.mapper.AccountMapper;
import net.lgy.mapper.StorageMapper;
import net.lgy.model.AccountDO;
import net.lgy.model.StorageDO;
import net.lgy.service.AccountFileService;
import net.lgy.service.AccountService;
import net.lgy.util.CommonUtil;
import org.apache.catalina.StoreManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountManager accountManager;

    @Autowired
    private StoreEngine storeEngine;
    @Autowired
    private AccountFileService accountFileService;

    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private StorageMapper storageMapper;


    @Override
    public String uploadAvatar(MultipartFile file) throws IOException {
//        处理后的文件名
        String fileName = CommonUtil.getFilePath(file.getOriginalFilename());
//        直接用封装好的类上传
        boolean upload = storeEngine.upload(minioConfig.getAvatarBucketName(), fileName, file);

        return minioConfig.getEndpoint()+"/"+minioConfig.getAvatarBucketName()+"/"+fileName;
    }

    @Override
    public void createDefaultBucket(AccountDO accountDO) {
//        创建默认存储空间
        StorageDO storageDO = new StorageDO();
        storageDO.setAccountNo(accountDO.getAccountNo());
        storageDO.setUsedSize(0L);
        storageDO.setTotalSize(AccountConfig.DEFAULT_SPACE_SIZE);
        storageMapper.insert(storageDO);

//        初始化根目录
        FolderCreateRequest createRootFolder = FolderCreateRequest.builder().accountNo(accountDO.getAccountNo())
                .parentId(AccountConfig.ROOT_FOLDER_PARENT_ID)
                .folderName(AccountConfig.ROOT_FOLDER_NAME).build();

        accountFileService.createFolder(createRootFolder);

    }

    @Override
    public AccountDTO login(AccountLoginRequest request) {
        String phone = request.getPhone();
        AccountDTO accountDTO = findByPhone(phone);
        return accountDTO;
    }


    @Override
    public AccountDTO findByPhone(String phone) {
        AccountDO accountDO = accountManager.findByPhone(phone);
        AccountDTO accountDTO  = new AccountDTO();
        BeanUtils.copyProperties(accountDO,accountDTO);
        return accountDTO;
    }
}
